<?php

namespace App\Admin\Controllers\Aliyun;

use App\Admin\Actions\Aliyun\DownloadCert;
use App\Enums\DomainSource;
use App\Models\Aliyun;
use App\Models\Ssl;
use Dcat\Admin\Exception\InvalidArgumentException;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use PhpZip\ZipFile;

class SslController extends AdminController
{
    protected string $title = 'SSL证书';

    protected array $description = [
        'index' => 'Let’sEncrypt证书',
    ];

    /**
     * @throws InvalidArgumentException
     */
    public function grid(): Grid
    {
        $model = Ssl::ofAdmin()
            ->orderBy('expires_at')
            ->latest();

//        AliyunDomainLetsEncrypt::dispatch(Ssl::first());

        return Grid::make($model, function (Grid $grid) {
            $grid->disableRowSelector();
            $grid->disableEditButton();

            $grid->actions([
                new DownloadCert,
            ]);

            $grid->column('type', '域名类型')
                ->using(DomainSource::SOURCE_MAP);
            $grid->column('证书域名')
                ->display(fn() => $this->ssl_domain);
            $grid->column('order_id', '订单编号')
                ->copyable();
            $grid->column('expiry_date', '过期时间')
                ->display(function ($date) {
                    if (now()->isAfter($date)) {
                        return "<span class='label' style='background:#ea5455'>$date</span>";
                    } elseif (now()->diffInDays($date) <= 14) {
                        return "<span class='label' style='background:#586cb1'>$date</span>";
                    } else {
                        return $date;
                    }
                });
            $grid->column('expires_at', '订单有效期');
            $grid->column('state', '当前状态');
            $grid->column('created_at');
        });
    }

    public function form(): Form
    {
        return Form::make(Ssl::ofAdmin(), function (Form $form) {
            $form->radio('type', '域名来源')
                ->required()
                ->options(DomainSource::SOURCE_MAP)
                ->default(DomainSource::ALIYUN->value)
                ->when(DomainSource::ALIYUN->value, function (Form $form) {
                    $form->select('aliyun_id', '云账户')
                        ->rules('required_if:source,'.DomainSource::ALIYUN->value)
                        ->options(Aliyun::ofAdmin()->pluck('name', 'id'))
                        ->load('root', route('admin.pools.domains'));
                    $form->select('root', '根域名')
                        ->rules('required_if:source,'.DomainSource::ALIYUN->value);
                    $form->text('rr', 'A记录')
                        ->rules('required_if:source,'.DomainSource::ALIYUN->value);
                })
                ->when(DomainSource::CUSTOM->value, function (Form $form) {
                    $form->text('domain', '域名地址')
                        ->rules('required_if:source,'.DomainSource::CUSTOM->value, [
                            'required_if' => '域名地址必须填写',
                        ]);
                });
        });
    }

    public function detail(string $id): void
    {
        $domain = Ssl::ofAdmin()->findOrFail($id);
        $certs = $domain->certs;

        $name = sprintf(
            '%s_%s',
            $domain->expires_at->format('Y_m_d'),
            str_replace(['*', '.'], ['all', '_'], $domain->ssl_domain),
        );

        $zipFile = new ZipFile();
        $zipFile->addFromString($name.'.pem', $certs['chain']);
        $zipFile->addFromString($name.'.key', $certs['privateKey']);

        $zipFile->outputAsAttachment($name.'.zip');
        $zipFile->close();
    }
}
